<!DOCTYPE html>












  


<html class="theme-next mist use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2"/>
<meta name="theme-color" content="#222">









  
  
  <link rel="stylesheet" media="all" href="/lib/Han/dist/han.min.css?v=3.3">




<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />



















  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.lug.ustc.edu.cn/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=6.4.2" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.jpg?v=6.4.2">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.jpg?v=6.4.2">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.jpg?v=6.4.2">


  <link rel="mask-icon" href="/images/logo.svg?v=6.4.2" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    version: '6.4.2',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  




  <meta property="og:type" content="article">
<meta property="og:title" content="利用itchat将微信群消息全部进行记录备份">
<meta property="og:url" content="https://devzhao.com/post/3667c486.html">
<meta property="og:site_name" content="学而时习之">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="http://qnfile.devzhao.com/blog/2019-03-18-050206.jpg">
<meta property="og:updated_time" content="2019-03-18T05:02:26.112Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="利用itchat将微信群消息全部进行记录备份">
<meta name="twitter:image" content="http://qnfile.devzhao.com/blog/2019-03-18-050206.jpg">






  <link rel="canonical" href="https://devzhao.com/post/3667c486.html"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>利用itchat将微信群消息全部进行记录备份 | 学而时习之</title>
  






  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?b8fcd96e6d9e134b3c9551097ed074a4";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  <div id="showImgFullScrn" style="display: none;"><img id="showImgFullScrnImg" src="" style="max-height:100%"></div>

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">学而时习之</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <h1 class="site-subtitle" itemprop="description">时间就是力量</h1>
      
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">
    <a href="/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-shortcut">
    <a href="/shortcut/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-shirtsinbulk"></i> <br />快捷</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">
    <a href="/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />归档</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">
    <a href="/categories/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-th"></i> <br />分类</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">
    <a href="/tags/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />标签</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-about">
    <a href="/about/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-user"></i> <br />关于</a>
  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />搜索</a>
        </li>
      
    </ul>
  

  
    

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://devzhao.com/post/3667c486.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="zhaohan">
      <meta itemprop="description" content="教，是最好的学">
      <meta itemprop="image" content="http://qnfile.devzhao.com/blog/2018-10-12-125720.jpg#/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="学而时习之">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">利用itchat将微信群消息全部进行记录备份
              
            
          </h2>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2019-03-18 12:52:14" itemprop="dateCreated datePublished" datetime="2019-03-18T12:52:14+08:00">2019-03-18</time>
            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/工具/" itemprop="url" rel="index"><span itemprop="name">工具</span></a></span>

                
                
                  ，
                
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/工具/微信/" itemprop="url" rel="index"><span itemprop="name">微信</span></a></span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/post/3667c486.html#comments" itemprop="discussionUrl">
                  <span class="post-meta-item-text">评论数：</span> <span class="post-comments-count valine-comment-count" data-xid="/post/3667c486.html" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          
             <span id="/post/3667c486.html" class="leancloud_visitors" data-flag-title="利用itchat将微信群消息全部进行记录备份">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数：</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          
            <div class="post-symbolscount">
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">本文字数：</span>
                
                <span title="本文字数">13k</span>
              

              

              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body han-init-context" itemprop="articleBody">

      
      

      
        <p><img class="zhao-img-h153" src="http://qnfile.devzhao.com/blog/2019-03-18-050206.jpg"></p>
<a id="more"></a>
<p><br>在微信社群运营的时候，有以下几个需求点：</p>
<ul>
<li>1.要统计每个社群的用户活跃度，及发言数量</li>
<li>2.要看到每个人的活跃度</li>
<li>3.要统计所有社群的发言，分析社群用户所关注的重点</li>
</ul>
<p>以下是利用itchat二次开发的一个记录微信消息的小工具。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br><span class="line">203</span><br><span class="line">204</span><br><span class="line">205</span><br><span class="line">206</span><br><span class="line">207</span><br><span class="line">208</span><br><span class="line">209</span><br><span class="line">210</span><br><span class="line">211</span><br><span class="line">212</span><br><span class="line">213</span><br><span class="line">214</span><br><span class="line">215</span><br><span class="line">216</span><br><span class="line">217</span><br><span class="line">218</span><br><span class="line">219</span><br><span class="line">220</span><br><span class="line">221</span><br><span class="line">222</span><br><span class="line">223</span><br><span class="line">224</span><br><span class="line">225</span><br><span class="line">226</span><br><span class="line">227</span><br><span class="line">228</span><br><span class="line">229</span><br><span class="line">230</span><br><span class="line">231</span><br><span class="line">232</span><br><span class="line">233</span><br><span class="line">234</span><br><span class="line">235</span><br><span class="line">236</span><br><span class="line">237</span><br><span class="line">238</span><br><span class="line">239</span><br><span class="line">240</span><br><span class="line">241</span><br><span class="line">242</span><br><span class="line">243</span><br><span class="line">244</span><br><span class="line">245</span><br><span class="line">246</span><br><span class="line">247</span><br><span class="line">248</span><br><span class="line">249</span><br><span class="line">250</span><br><span class="line">251</span><br><span class="line">252</span><br><span class="line">253</span><br><span class="line">254</span><br><span class="line">255</span><br><span class="line">256</span><br><span class="line">257</span><br><span class="line">258</span><br><span class="line">259</span><br><span class="line">260</span><br><span class="line">261</span><br><span class="line">262</span><br><span class="line">263</span><br><span class="line">264</span><br><span class="line">265</span><br><span class="line">266</span><br><span class="line">267</span><br><span class="line">268</span><br><span class="line">269</span><br><span class="line">270</span><br><span class="line">271</span><br><span class="line">272</span><br><span class="line">273</span><br><span class="line">274</span><br><span class="line">275</span><br><span class="line">276</span><br><span class="line">277</span><br><span class="line">278</span><br><span class="line">279</span><br><span class="line">280</span><br><span class="line">281</span><br><span class="line">282</span><br><span class="line">283</span><br><span class="line">284</span><br><span class="line">285</span><br><span class="line">286</span><br><span class="line">287</span><br><span class="line">288</span><br><span class="line">289</span><br><span class="line">290</span><br><span class="line">291</span><br><span class="line">292</span><br><span class="line">293</span><br><span class="line">294</span><br><span class="line">295</span><br></pre></td><td class="code"><pre><span class="line">#coding=utf8</span><br><span class="line">import itchat</span><br><span class="line">from itchat.content import *</span><br><span class="line">import pymysql</span><br><span class="line">import os</span><br><span class="line">import uuid</span><br><span class="line">import hashlib</span><br><span class="line">import time</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"># 连接配置信息</span><br><span class="line">config = &#123;</span><br><span class="line">    &apos;你的数据库配置&apos;,</span><br><span class="line">&#125;</span><br><span class="line"># 创建连接</span><br><span class="line">connection = pymysql.connect(**config)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">def mkdir(path):</span><br><span class="line">    isExists = os.path.exists(path)</span><br><span class="line">    if not isExists:</span><br><span class="line">        os.makedirs(path)</span><br><span class="line">        return True</span><br><span class="line">    else:</span><br><span class="line">        return False</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">def md5_key(arg):</span><br><span class="line">    hash = hashlib.md5()</span><br><span class="line">    hash.update(arg.encode())</span><br><span class="line">    return hash.hexdigest()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">def get_values(obj, keys,  format_str=False):</span><br><span class="line">    aList = []</span><br><span class="line">    for key in keys:</span><br><span class="line">        try:</span><br><span class="line">            value = obj[key]</span><br><span class="line">            if format_str:</span><br><span class="line">                value = str(value)</span><br><span class="line">            aList.append(value)</span><br><span class="line">        except Exception as e:</span><br><span class="line">            print(&apos;------ERROR---------&apos;, e)</span><br><span class="line">            aList.append(&apos;&apos;)</span><br><span class="line"></span><br><span class="line">    return tuple(aList)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">#添加群信息</span><br><span class="line">def add_group(groupUserName):</span><br><span class="line">    group = itchat.search_chatrooms(userName=groupUserName)</span><br><span class="line">    group_keys = (&apos;Uin&apos;, &apos;UserName&apos;, &apos;NickName&apos;, &apos;HeadImgUrl&apos;, &apos;ContactFlag&apos;, &apos;MemberCount&apos;, &apos;RemarkName&apos;,</span><br><span class="line">                 &apos;HideInputBarFlag&apos;, &apos;Sex&apos;, &apos;Signature&apos;, &apos;VerifyFlag&apos;, &apos;OwnerUin&apos;, &apos;PYInitial&apos;, &apos;PYQuanPin&apos;,</span><br><span class="line">                 &apos;RemarkPYInitial&apos;, &apos;RemarkPYQuanPin&apos;, &apos;StarFriend&apos;, &apos;AppAccountFlag&apos;, &apos;Statues&apos;, &apos;AttrStatus&apos;,</span><br><span class="line">                 &apos;Province&apos;, &apos;City&apos;, &apos;Alias&apos;, &apos;SnsFlag&apos;, &apos;UniFriend&apos;, &apos;DisplayName&apos;, &apos;ChatRoomId&apos;, &apos;KeyWord&apos;,</span><br><span class="line">                 &apos;EncryChatRoomId&apos;, &apos;IsOwner&apos;, &apos;IsAdmin&apos;)</span><br><span class="line"></span><br><span class="line">    group_tuple = get_values(group, group_keys)</span><br><span class="line"></span><br><span class="line">    self = group[&apos;Self&apos;]</span><br><span class="line">    self_keys = (&apos;Uin&apos;, &apos;UserName&apos;, &apos;NickName&apos;, &apos;AttrStatus&apos;, &apos;PYInitial&apos;, &apos;PYQuanPin&apos;, &apos;RemarkPYInitial&apos;,</span><br><span class="line">                 &apos;RemarkPYQuanPin&apos;, &apos;MemberStatus&apos;, &apos;DisplayName&apos;, &apos;KeyWord&apos;,)</span><br><span class="line">    self_tuple = get_values(self, self_keys, &quot;self&quot;)</span><br><span class="line"></span><br><span class="line">    param = group_tuple + self_tuple</span><br><span class="line"></span><br><span class="line">    connection.ping(connection)</span><br><span class="line">    try:</span><br><span class="line">        with connection.cursor() as cursor:</span><br><span class="line"></span><br><span class="line">            sql = &apos;INSERT INTO website_weixin_group (&apos; \</span><br><span class="line">                  &apos;`uin`,`user_name`,`nick_name`,`head_img_url`,`contact_flag`,`member_count`,`remark_name`,&apos; \</span><br><span class="line">                  &apos;`hide_input_bar_flag`,`sex`,`signature`,`verify_flag`,`owner_uin`,`py_initial`,`py_quan_pin`,&apos; \</span><br><span class="line">                  &apos;`remark_py_initial`,`remark_py_quan_pin`,`star_friend`,`app_account_flag`,`statues`,`attr_status`,&apos; \</span><br><span class="line">                  &apos;`province`,`city`,`alias`,`sns_flag`,`uni_friend`,`display_name`,`chat_room_id`,`key_word`,&apos; \</span><br><span class="line">                  &apos;`encry_chat_room_id`,`is_owner`,`is_admin`,`self_uin`, `self_user_name`, `self_nick_name`, &apos; \</span><br><span class="line">                  &apos;`self_attr_status`, `self_py_initial`, `self_py_quan_pin`, `self_remark_py_initial`, &apos; \</span><br><span class="line">                  &apos;`self_remark_py_quan_pin`, `self_member_status`, `self_display_name`, `self_key_word`&apos; \</span><br><span class="line">                  &apos;) VALUES(&apos; \</span><br><span class="line">                  &apos;%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,&apos; \</span><br><span class="line">                  &apos;%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,&apos; \</span><br><span class="line">                  &apos;%s,%s&apos; \</span><br><span class="line">                  &apos;)&apos;</span><br><span class="line"></span><br><span class="line">            print(sql)</span><br><span class="line">            print(param)</span><br><span class="line"></span><br><span class="line">            result = cursor.execute(sql, param)</span><br><span class="line">        # 没有设置默认自动提交，需要主动提交，以保存所执行的语句</span><br><span class="line">        connection.commit()</span><br><span class="line">        print(&apos;++++++++++++++++数据库保存成功:&apos; + result)</span><br><span class="line">    except Exception as e:</span><br><span class="line">        print(&apos;-----------------数据库保存错误&apos;, e)</span><br><span class="line">        connection.close()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">#保存群消息</span><br><span class="line">def save_group(groupUserName, group_member_count):</span><br><span class="line"></span><br><span class="line">    add_group_flag = False</span><br><span class="line">    update_group_flag = False</span><br><span class="line">    find_param = (groupUserName)</span><br><span class="line">    connection.ping(connection)</span><br><span class="line">    try:</span><br><span class="line">        with connection.cursor() as cursor:</span><br><span class="line"></span><br><span class="line">            sql = &apos;SELECT * FROM website_weixin_group tb WHERE tb.user_name= %s&apos;</span><br><span class="line"></span><br><span class="line">            print(sql)</span><br><span class="line">            print(find_param)</span><br><span class="line"></span><br><span class="line">            exe_res = cursor.execute(sql, find_param)</span><br><span class="line">            if exe_res == 0:</span><br><span class="line">                add_group_flag = True</span><br><span class="line">            else:</span><br><span class="line">                result = cursor.fetchone()</span><br><span class="line">                print(&apos;+++++++++++查询到的群信息：&apos;, exe_res, result)</span><br><span class="line">                if result[&apos;member_count&apos;] != group_member_count:</span><br><span class="line">                    update_group_flag = True</span><br><span class="line">                    group_member_count = result[&apos;member_count&apos;]</span><br><span class="line">    except Exception as e:</span><br><span class="line">        print(&apos;-----------------数据库保存错误&apos;, e)</span><br><span class="line">        connection.close()</span><br><span class="line"></span><br><span class="line">    if add_group_flag:</span><br><span class="line">        add_group(groupUserName)</span><br><span class="line">        return</span><br><span class="line"></span><br><span class="line">    if not update_group_flag:</span><br><span class="line">        return</span><br><span class="line"></span><br><span class="line">    param = (group_member_count, groupUserName)</span><br><span class="line"></span><br><span class="line">    connection.ping(connection)</span><br><span class="line">    try:</span><br><span class="line">        with connection.cursor() as cursor:</span><br><span class="line"></span><br><span class="line">            sql = &apos;UPDATE website_weixin_group tb SET tb.member_count =  %s  WHERE tb.user_name= %s &apos;</span><br><span class="line"></span><br><span class="line">            print(sql)</span><br><span class="line">            print(param)</span><br><span class="line"></span><br><span class="line">            result = cursor.execute(sql, param)</span><br><span class="line">        # 没有设置默认自动提交，需要主动提交，以保存所执行的语句</span><br><span class="line">        connection.commit()</span><br><span class="line">        print(&apos;++++++++++++++++数据库保存成功:&apos; + result)</span><br><span class="line">    except Exception as e:</span><br><span class="line">        print(&apos;-----------------数据库保存错误&apos;, e)</span><br><span class="line">        connection.close()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">#保存群消息</span><br><span class="line">def save_group_msg(msg):</span><br><span class="line"></span><br><span class="line">    msg_keys = (&apos;Type&apos;,&apos;Text&apos;,&apos;MsgId&apos;, &apos;FromUserName&apos;, &apos;ToUserName&apos;, &apos;MsgType&apos;, &apos;Content&apos;, &apos;Status&apos;, &apos;ImgStatus&apos;, &apos;CreateTime&apos;,</span><br><span class="line">                &apos;VoiceLength&apos;, &apos;PlayLength&apos;, &apos;FileName&apos;, &apos;FileSize&apos;, &apos;MediaId&apos;, &apos;Url&apos;, &apos;AppMsgType&apos;, &apos;StatusNotifyCode&apos;,</span><br><span class="line">                &apos;StatusNotifyUserName&apos;, &apos;ForwardFlag&apos;, &apos;HasProductId&apos;, &apos;Ticket&apos;, &apos;ImgHeight&apos;, &apos;ImgWidth&apos;, &apos;SubMsgType&apos;,</span><br><span class="line">                &apos;NewMsgId&apos;, &apos;OriContent&apos;, &apos;EncryFileName&apos;, &apos;ActualNickName&apos;, &apos;IsAt&apos;, &apos;ActualUserName&apos;, )</span><br><span class="line">    msg_tuple = get_values(msg, msg_keys, True)</span><br><span class="line"></span><br><span class="line">    user = msg[&apos;User&apos;]</span><br><span class="line">    user_keys = (&apos;Uin&apos;, &apos;UserName&apos;, &apos;NickName&apos;, &apos;HeadImgUrl&apos;, &apos;ContactFlag&apos;, &apos;MemberCount&apos;,</span><br><span class="line">                    &apos;RemarkName&apos;, &apos;HideInputBarFlag&apos;, &apos;Sex&apos;, &apos;Signature&apos;, &apos;VerifyFlag&apos;,</span><br><span class="line">                    &apos;OwnerUin&apos;, &apos;PYInitial&apos;, &apos;PYQuanPin&apos;, &apos;RemarkPYInitial&apos;, &apos;RemarkPYQuanPin&apos;,</span><br><span class="line">                    &apos;StarFriend&apos;, &apos;AppAccountFlag&apos;, &apos;Statues&apos;, &apos;AttrStatus&apos;, &apos;Province&apos;, &apos;City&apos;,</span><br><span class="line">                    &apos;Alias&apos;, &apos;SnsFlag&apos;, &apos;UniFriend&apos;, &apos;DisplayName&apos;, &apos;ChatRoomId&apos;, &apos;KeyWord&apos;,</span><br><span class="line">                    &apos;EncryChatRoomId&apos;, &apos;IsOwner&apos;, &apos;IsAdmin&apos;)</span><br><span class="line">    user_tuple = get_values(user, user_keys, True)</span><br><span class="line"></span><br><span class="line">    self = user[&apos;Self&apos;]</span><br><span class="line">    self_keys = (&apos;UserName&apos;, &apos;NickName&apos;, &apos;AttrStatus&apos;)</span><br><span class="line">    self_tuple = get_values(self, self_keys)</span><br><span class="line"></span><br><span class="line">    param = msg_tuple + user_tuple + self_tuple</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    # 保存群信息</span><br><span class="line">    save_group(user[&apos;UserName&apos;], user[&apos;MemberCount&apos;])</span><br><span class="line"></span><br><span class="line">    #保存消息信息</span><br><span class="line">    connection.ping(connection)</span><br><span class="line">    try:</span><br><span class="line">        with connection.cursor() as cursor:</span><br><span class="line">            sql = &apos;INSERT INTO website_weixin_group_msg (&apos; \</span><br><span class="line">                  &apos;`type`,`text`,`msg_id`,`from_user_name`,`to_user_name`,`msg_type`,`content`,`status`,`img_status`,&apos; \</span><br><span class="line">                  &apos;`create_time`,`voice_length`,`play_length`,&apos; \</span><br><span class="line">                  &apos;`file_name`,`file_size`,`media_id`,`url`,`app_msg_type`,`status_notify_code`,&apos; \</span><br><span class="line">                  &apos;`status_notify_user_name`,`forward_flag`,&apos; \</span><br><span class="line">                  &apos;`has_product_id`,`ticket`,`img_height`,`img_width`,`sub_msg_type`,`new_msg_id`,`ori_content`,&apos; \</span><br><span class="line">                  &apos;`encry_file_name`,`actual_nick_name`,`is_at`,&apos; \</span><br><span class="line">                  &apos;`actual_user_name`,`user_uin`,`user_user_name`,`user_nick_name`, `user_head_img_url`, &apos; \</span><br><span class="line">                  &apos;`user_contact_flag`,`user_member_count`,`user_remark_name`,`user_hide_input_bar_flag`,`user_sex`,&apos; \</span><br><span class="line">                  &apos;`user_signature`,`user_verify_flag`,`user_owner_uin`,`user_py_initial`,`user_py_quan_pin`,&apos; \</span><br><span class="line">                  &apos;`user_remark_py_initial`,&apos; \</span><br><span class="line">                  &apos;`user_remark_py_quan_pin`,`user_star_friend`,`user_app_account_flag`,`user_statues`,&apos; \</span><br><span class="line">                  &apos;`user_attr_status`,`user_province`,&apos; \</span><br><span class="line">                  &apos;`user_city`,`user_alias`,`user_sns_flag`,`user_uni_friend`,`user_display_name`,`user_chat_room_id`,&apos; \</span><br><span class="line">                  &apos;`user_key_word`,&apos; \</span><br><span class="line">                  &apos;`user_encry_chat_room_id`,`user_is_owner`,`user_is_admin`,`user_self_user_name`,&apos; \</span><br><span class="line">                  &apos;`user_self_nick_name`,`user_self_attr_status`&apos; \</span><br><span class="line">                  &apos;) VALUES(&apos; \</span><br><span class="line">                  &apos;%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,&apos; \</span><br><span class="line">                  &apos;%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,&apos; \</span><br><span class="line">                  &apos;%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,&apos; \</span><br><span class="line">                  &apos;%s,%s,%s,%s,%s&apos; \</span><br><span class="line">                  &apos;)&apos;</span><br><span class="line"></span><br><span class="line">            print(sql)</span><br><span class="line">            print(param)</span><br><span class="line">            result = cursor.execute(sql, param)</span><br><span class="line"></span><br><span class="line">        # 没有设置默认自动提交，需要主动提交，以保存所执行的语句</span><br><span class="line">        connection.commit()</span><br><span class="line">        print(&apos;++++++++++++++++数据库保存成功:&apos; + result)</span><br><span class="line">    except Exception as e:</span><br><span class="line">        print(&apos;-----------------数据库保存错误&apos;, e)</span><br><span class="line">        connection.close()</span><br><span class="line"></span><br><span class="line">    return cursor.lastrowid</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">def save_msg_attach(msgSid, wxMsgId, fileKey, weixin_msg_type, file_name, file_size):</span><br><span class="line"></span><br><span class="line">    connection.ping(connection)</span><br><span class="line">    try:</span><br><span class="line">        with connection.cursor() as cursor:</span><br><span class="line">            sql = &apos;INSERT INTO website_weixin_msg_attach (&apos; \</span><br><span class="line">                  &apos;`msg_sid`,`weixin_msg_id`,`weixin_msg_type`,`mime_type`,`file_key`,`file_name`,`file_size`&apos; \</span><br><span class="line">                  &apos;) VALUES(&apos; \</span><br><span class="line">                  &apos;%s,%s,%s,%s,%s,%s,%s&apos; \</span><br><span class="line">                  &apos;)&apos;</span><br><span class="line"></span><br><span class="line">            param = (msgSid, wxMsgId, weixin_msg_type, &apos;mime_type&apos;, fileKey, file_name, file_size)</span><br><span class="line"></span><br><span class="line">            print(sql)</span><br><span class="line">            print(param)</span><br><span class="line"></span><br><span class="line">            result = cursor.execute(sql, param)</span><br><span class="line">        # 没有设置默认自动提交，需要主动提交，以保存所执行的语句</span><br><span class="line">        connection.commit()</span><br><span class="line">        print(&apos;++++++++++++++++数据库保存成功:&apos; + result)</span><br><span class="line">    except Exception as e:</span><br><span class="line">        print(&apos;-----------------数据库保存错误&apos;, e)</span><br><span class="line">        connection.close()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"># @itchat.msg_register(FRIENDS)</span><br><span class="line"># def add_friend(msg):</span><br><span class="line">#     print(&apos;add_friend&apos;, msg)</span><br><span class="line">#     msg.user.verify()</span><br><span class="line">#     msg.user.send(&apos;Nice to meet you!&apos;)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">@itchat.msg_register([TEXT, MAP, CARD, NOTE, SHARING], isGroupChat=True)</span><br><span class="line">def rec_text_msg(msg):</span><br><span class="line">    print(&apos;msg:&apos;, msg)</span><br><span class="line">    save_group_msg(msg)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">root_folder = &apos;files/&apos;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">@itchat.msg_register([PICTURE, RECORDING, ATTACHMENT, VIDEO], isGroupChat=True)</span><br><span class="line">def rec_file_msg(msg):</span><br><span class="line">    Type = msg[&apos;Type&apos;]</span><br><span class="line">    print(&apos;Type:&apos;, Type)</span><br><span class="line"></span><br><span class="line">    uuidstr = uuid.uuid4()</span><br><span class="line">    nowTime = time.time()</span><br><span class="line">    uuidstr = str(uuidstr) + str(nowTime)</span><br><span class="line">    print(type(uuidstr), uuidstr)</span><br><span class="line"></span><br><span class="line">    path_prefix = &apos;wechatboot/group_msg_attach/&apos;</span><br><span class="line">    folder = &apos;./&apos; + root_folder + path_prefix</span><br><span class="line">    mkdir(folder)</span><br><span class="line"></span><br><span class="line">    md5str = md5_key(uuidstr)</span><br><span class="line">    file_name = md5str + os.path.splitext(msg.fileName)[1]</span><br><span class="line">    file_key = path_prefix + file_name</span><br><span class="line"></span><br><span class="line">    file_path = root_folder + &apos;/&apos; + file_key</span><br><span class="line">    msg.download(file_path)</span><br><span class="line"></span><br><span class="line">    msgSid = save_group_msg(msg)</span><br><span class="line">    wxMsgId = msg[&apos;MsgId&apos;]</span><br><span class="line">    fileKey = file_key</span><br><span class="line">    MsgType = str(msg[&apos;MsgType&apos;])</span><br><span class="line">    file_name = str(msg[&apos;FileName&apos;])</span><br><span class="line">    file_size = str(msg[&apos;FileSize&apos;])</span><br><span class="line">    save_msg_attach(msgSid, wxMsgId, fileKey, MsgType, file_name, file_size)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">itchat.auto_login(hotReload=True, enableCmdQR=False)</span><br><span class="line">itchat.run(True)</span><br></pre></td></tr></table></figure>

      
    </div>

    

    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持分享输出，感谢你的支持！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatpay.jpg" alt="zhaohan 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.jpg" alt="zhaohan 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>zhaohan</li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://devzhao.com/post/3667c486.html" title="利用itchat将微信群消息全部进行记录备份">https://devzhao.com/post/3667c486.html</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明出处！</li>
</ul>

      </div>
    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/post/92ba7c4f.html" rel="next" title="spark邮箱配置163邮箱">
                <i class="fa fa-chevron-left"></i> spark邮箱配置163邮箱
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/post/326c39e5.html" rel="prev" title="关于seo的简单概念">
                关于seo的简单概念 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="http://qnfile.devzhao.com/blog/2018-10-12-125720.jpg#/images/avatar.gif"
                alt="zhaohan" />
            
              <p class="site-author-name" itemprop="name">zhaohan</p>
              <p class="site-description motion-element" itemprop="description">教，是最好的学</p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">148</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">33</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">29</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          

          

          
          

          
          

          
            
          
          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">zhaohan</span>

  

  
</div>


  










        
<div class="busuanzi-count">
  <!--<script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>-->

  <script async src="//cdn.busuanzi.ibruce.info/cdn/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv" title="总访客量">
      <!-- <i class="fa fa-user-circle"></i> -->
      <i>已有</i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      <i>位访客浏览过此网站</i>
    </span>
  

  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    
	
    

    
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.4.2"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.4.2"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.4.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.4.2"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.4.2"></script>



  



  








  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  
  
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick';
    guest = guest.split(',').filter(function (item) {
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: true,
        notify: false,
        appId: 'z99UqRJEaGqxYLDPSPSx5jih-gzGzoHsz',
        appKey: 'N7MTJbRdufk8MAg3yeK6Gs9U',
        placeholder: '说点什么吧...',
        avatar:'mm',
        meta:guest,
        pageSize:'10' || 10,
        visitor: false
    });
  </script>



  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script>
    
    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();

      Counter('get', '/classes/Counter', { where: JSON.stringify({ url }) })
        .done(function ({ results }) {
          if (results.length > 0) {
            var counter = results[0];
            
            Counter('put', `/classes/Counter/${counter.objectId}`, JSON.stringify({ time: { "__op":"Increment", "amount":1 } }))
            
            .done(function () {
                  var $element = $(document.getElementById(url));
                  $element.find('.leancloud-visitors-count').text(counter.time + 1);
            })
            
            .fail(function ({ responseJSON }) {
                console.log('Failed to save Visitor num, with error message: ' + responseJSON.error);
            })
          } else {
            
              Counter('post', '/classes/Counter', JSON.stringify({ title: title, url: url, time: 1}))
                .done(function () {
                  var $element = $(document.getElementById(url));
                  $element.find('.leancloud-visitors-count').text(1);
                })
                .fail(function () {
                  console.log('Failed to create');
                });
            
          }
        })
      .fail(function ({ responseJSON }) {
        console.log('LeanCloud Counter Error:' + responseJSON.code + " " + responseJSON.error);
      });
    }
    

    $(function() {
      $.get('https://app-router.leancloud.cn/2/route?appId=' + "z99UqRJEaGqxYLDPSPSx5jih-gzGzoHsz")
        .done(function ({ api_server }) {
          var Counter = function (method, url, data) {
            return $.ajax({
              method: method,
              url: `https://${api_server}/1.1${url}`,
              headers: {
                'X-LC-Id': "z99UqRJEaGqxYLDPSPSx5jih-gzGzoHsz",
                'X-LC-Key': "N7MTJbRdufk8MAg3yeK6Gs9U",
                'Content-Type': 'application/json',
              },
              data: data,
            });
          };
          
          addCount(Counter);
          
        })
    });
  </script>



  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  

  
  

  

  

  

  

  

</body>
</html>
